<template>
  <div>
    <Row>
      <Col span="8">
        <Card bordered>
          <p slot="title">字典目录</p>
          <div>
            <Input placeholder="输入关键字进行过滤" v-model="filterText"/>
            <Tree :data="dictTypeData" ref="dictTypeTree" :render="renderContent"></Tree>
          </div>
        </Card>
      </Col>
      <Col span="16">
        <Card v-if="!editDictTypeFlag">
          <p slot="title">字典值</p>
          <div>
            <Tables ref="table" searchable search-place="top" :columns="columns" v-model="dictValueTableData">
              <template slot="handleButton">
                <Button v-if="dictValueManager_btn_add" type="primary" @click="handleDictValueCreate"><Icon type="md-add">新增</Icon></Button>
              </template>
              <template slot="searchButton">
                <div style="float:right">
                  <Input @keyup.enter.native="handleDictValueFilter" placeholder="标签或code" class="search-input" v-model="listDictValueQuery.labelDefault">
                    <Button @click="handleDictValueFilter" slot="append" type="info" icon="ios-search"></Button>
                  </Input>
                </div>
              </template>
              <template slot="action" slot-scope="scope">
                <Button v-if="dictValueManager_btn_edit" type="success" size="small" @click="handleClick(scope.row)">修改</Button>
                <Button v-if="dictValueManager_btn_del" type="warning" size="small" @click="handleDelete(scope.row)">删除</Button>
              </template>
            </Tables>
          </div>
        </Card>
        <Card v-if="editDictTypeFlag">
          <p slot="title">目录编辑</p>
          <Form ref="dictTypeForm" :model="dictTypeForm" :label-width="100" :rules="dictTypeFormRules">
            <FormItem label="编码值" prop="code">
              <Input v-model="dictTypeForm.code" placeholder="请输入编码">
              </Input>
            </FormItem>
            <FormItem label="目录名" prop="labelDefault">
              <Input v-model="dictTypeForm.name" placeholder="请输入目录名"/>
            </FormItem>
            <FormItem>
              <Button type="success" @click="handlerDictTypeForm('dictTypeForm')" v-if="this.dictTypeManager_btn_edit">确 定</Button>
              <Button type="primary" @click="editDictTypeFlag=false">取消</Button>
            </FormItem>
          </Form>
        </Card>
      </Col>
    </Row>
    <Modal title="提示" v-model="dictValueDialogVisible" :mask-closable='false' :width="30">
      <Form ref="dictValueForm" :model="dictValueForm" :label-width="100" :rules="dictValueFormRules">
        <FormItem label="编码值" prop="code">
          <Input v-model="dictValueForm.code" placeholder="请输入值">
            <span slot="prepend">{{currentDictType.code+'_'}}</span>
          </Input>
        </FormItem>
        <FormItem label="默认显示" prop="labelDefault">
          <Input v-model="dictValueForm.labelDefault" placeholder="请输入默认显示"/>
        </FormItem>
        <FormItem label="英文显示" prop="serviceId">
          <Input  v-model="dictValueForm.labelEnUs" placeholder="请输入英文显示"/>
        </FormItem>
        <FormItem label="中文显示" prop="labelZhCh">
          <Input  v-model="dictValueForm.labelZhCh" placeholder="请输入中文显示"/>
        </FormItem>
        <FormItem label="排序" prop="orderNum">
          <Input v-model="dictValueForm.orderNum" placeholder="请输入排序"/>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text" @click="handleDictValueCancel">取消</Button>
        <Button type="primary" @click="handleDictValueSave('dictValueForm')">确 定</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import {
  getTree,
  addTypeObj,
  getTypeObj,
  delTypeObj,
  putTypeObj
} from '@/api/dict/dictType/index'
import {
  page,
  addValueObj,
  delValueObj,
  putValueObj
} from '@/api/dict/dictValue/index'
import { convertTree } from '@/libs/util'
import { mapGetters } from 'vuex'
import Tables from '_c/tables'
export default {
  components: {
    Tables
  },
  // watch: {
  //   filterText (val) {
  //     this.$refs.dictTypeTree.filter(val)
  //   }
  // },
  methods: {
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleClick (row) {
      this.dictValueDialogVisible = true
      const { ...obj } = row
      this.dictValueForm = obj
      if (this.dictValueForm.code.indexOf(this.currentDictType.code) > -1) {
        this.dictValueForm.code = this.dictValueForm.code.substring(this.currentDictType.code.length + 1, this.dictValueForm.code.length)
      }
    },
    handleDelete (row) {
      this.$Modal.confirm({
        title: '提示',
        content: '此操作将永久删除字典值, 是否继续?',
        onOk: () => {
          delValueObj(row.id).then(() => {
            this.getNodeData(this.nodeData)
            this.$Notice.success({
              title: '成功',
              message: '删除成功'
            })
          })
        }
      })
    },
    handleDictValueFilter () {
      this.listDictValueQuery.typeId = this.currentDictTypeId
      page(this.listDictValueQuery).then(response => {
        this.dictValueTableData = response.data.rows
      })
    },
    handleDictValueSave (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          if (this.dictValueForm.id !== undefined) {
            this.dictValueForm.value = this.dictValueForm.code
            this.dictValueForm.code = this.currentDictType.code + '_' + this.dictValueForm.code
            putValueObj(this.dictValueForm.id, this.dictValueForm).then(() => {
              this.editDictTypeFlag = false
              this.handleDictValueFilter()
              this.$Notice.success({
                title: '成功',
                message: '修改成功'
              })
              this.dictValueDialogVisible = false
            })
          } else {
            this.dictValueForm.value = this.dictValueForm.code
            this.dictValueForm.code = this.currentDictType.code + '_' + this.dictValueForm.code
            this.dictValueForm.typeId = this.currentDictTypeId
            addValueObj(this.dictValueForm).then(() => {
              this.editDictTypeFlag = false
              this.handleDictValueFilter()
              this.$Notice.success({
                title: '成功',
                message: '添加成功'
              })
              this.dictValueDialogVisible = false
            })
          }
        } else {
          return false
        }
      })
    },
    handleDictValueCreate () {
      if (this.currentDictTypeId === undefined) {
        this.$Notice.warning({
          title: '失败',
          message: '请先选择字典目录'
        })
      } else {
        this.dictValueDialogVisible = true
        this.resetDictValueForm()
      }
    },
    handleDictValueCancel () {
      this.dictValueDialogVisible = false
      this.resetDictValueForm()
    },
    handlerDictTypeForm (formName) {
      const set = this.$refs
      set[formName].validate(valid => {
        if (valid) {
          putTypeObj(this.dictTypeForm.id, this.dictTypeForm).then(() => {
            this.editDictTypeFlag = false
            this.initTreeData()
            this.$Notice.success({
              title: '成功',
              message: '修改成功'
            })
          })
        } else {
          return false
        }
      })
    },
    append (node, data) {
      let entity = {}
      addTypeObj({ name: '子节点', code: data.code + '_tmp', parentId: data.id }).then(response => {
        entity = response.data
        const newChild = { id: entity.id, title: entity.name, children: [] }
        if (!data.children) {
          this.$set(data, 'children', [])
        }
        data.children.push(newChild)
      })
      // this.$refs.dictTypeTree.setCurrentKey(data.id)
    },
    remove (node, data) {
      if (data.children.length > 0) {
        this.$Notice.error({
          title: '失败',
          desc: '删除失败，该项有子孙节点！'
        })
        return
      }
      const query = {
        typeId: this.currentDictTypeId
      }
      page(query).then(response => {
        this.dictValueTableData = response.data.rows
        if (this.dictValueTableData.length > 0) {
          this.$Notice.error({
            title: '失败',
            desc: '删除失败，该项有字典值！'
          })
          return
        }
        delTypeObj(data.id).then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '删除成功'
          })
          this.initTreeData()
          // const parent = node.parent
          // const children = parent.data.children || parent.data
          // const index = children.findIndex(d => d.id === data.id)
          // children.splice(index, 1)
        })
        // this.$refs.dictTypeTree.setCurrentKey(data.id)
      })
    },
    edit (node, data) {
      this.editDictTypeFlag = true
      this.currentDictTypeId = data.id
      this.currentDictType = data
      getTypeObj(data.id).then(response => {
        this.dictTypeForm = response.data
      })
      // this.$refs.dictTypeTree.setCurrentKey(data.id)
    },
    resetDictTypeForm () {
      this.dictTypeForm = {
        code: '',
        name: ''
      }
    },
    resetDictValueForm () {
      this.dictValueForm = {
        code: undefined,
        labelDefault: undefined,
        labelEnUs: undefined,
        labelZhCh: undefined,
        value: undefined
      }
    },
    renderContent (h, { root, node, data }) {
      return h('span', {
        style: {
          display: 'inline-block',
          width: '100%'
        },
        on: {
          click: () => {
            this.nodeData = data
            this.getNodeData(data)
          }
        },
        class: {
          'ivu-tree-title': true
        }
      },
      [
        h('span', [
          h('Icon', {
            props: {
              type: 'ios-folder-outline'
            },
            style: {
              marginRight: '8px'
            }
          }),
          h('span', data.title)
        ]),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '32px'
          }
        }, [
          this.dictTypeManager_btn_edit ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-create',
              type: 'primary'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.edit(node, data) }
            }
          }) : h('span'),
          this.dictTypeManager_btn_add ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-add',
              type: 'primary'
            }),
            style: {
              marginRight: '8px'
            },
            on: {
              click: () => { this.append(node, data) }
            }
          }) : h('span'),
          this.dictTypeManager_btn_del ? h('Button', {
            props: Object.assign({}, this.buttonProps, {
              icon: 'ios-trash',
              type: 'primary'
            }),
            on: {
              click: () => { this.remove(node, data) }
            }
          }) : h('span')
        ])
      ])
    },
    initTreeData () {
      getTree().then(data => {
        const map = {
          value: 'id',
          label: 'label',
          children: 'children',
          childExpand: true
        }
        this.dictTypeData = convertTree(data, map)
      })
    },
    getNodeData (data) {
      this.currentDictTypeId = data.id
      getTypeObj(data.id).then(response => {
        this.currentDictType = response.data
      })
      const query = {
        typeId: this.currentDictTypeId
      }
      page(query).then(response => {
        this.dictValueTableData = response.data.rows
      })
    }
  },
  created () {
    this.initTreeData()
    // 加载树
    this.dictTypeManager_btn_edit = this.elements['dictTypeManager:btn_edit']
    this.dictTypeManager_btn_del = this.elements['dictTypeManager:btn_del']
    this.dictTypeManager_btn_add = this.elements['dictTypeManager:btn_add']
    this.dictValueManager_btn_edit = this.elements['dictValueManager:btn_edit']
    this.dictValueManager_btn_del = this.elements['dictValueManager:btn_del']
    this.dictValueManager_btn_add = this.elements['dictValueManager:btn_add']
  },
  computed: {
    ...mapGetters(['elements'])
  },
  data () {
    return {
      buttonProps: {
        type: 'default',
        size: 'small'
      },
      nodeData: undefined,
      columns: [
        { title: '操作',
          key: 'action',
          align: 'center',
          render: (h, params) => {
            return h(
              'div',
              this.$refs.table.$scopedSlots.action(params)
            )
          }
        },
        { title: '编码', key: 'code' },
        { title: '值', key: 'value' },
        { title: '默认显示', key: 'labelDefault' },
        { title: '排序', key: 'orderNum' },
        { title: '英文显示', key: 'labelEnUs' },
        { title: '中文显示', key: 'labelZhCh' }
      ],
      dictValueManager_btn_edit: false,
      dictValueManager_btn_del: false,
      dictValueManager_btn_add: false,
      dictTypeManager_btn_edit: false,
      dictTypeManager_btn_del: false,
      dictTypeManager_btn_add: false,
      filterText: '',
      dictValueDialogVisible: false,
      editDictTypeFlag: false,
      currentDictTypeId: undefined,
      currentDictType: {},
      dictTypeForm: {
        code: '',
        name: ''
      },
      listDictValueQuery: {
        labelDefault: undefined,
        typeId: undefined
      },
      dictValueForm: {
        code: undefined,
        labelDefault: undefined,
        labelEnUs: undefined,
        labelZhCh: undefined,
        value: undefined
      },
      dictValueFormRules: {
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        labelDefault: [
          {
            required: true,
            message: '请输入默认显示',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        labelEnUs: [
          {
            required: true,
            message: '请输入英文显示',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        labelZhCh: [
          {
            required: true,
            message: '请输入中文显示',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      dictTypeFormRules: {
        code: [
          {
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        name: [
          {
            required: true,
            message: '请输入目录名',
            trigger: 'blur'
          },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      dictTypeData: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dictValueTableData: []
    }
  }
}

</script>
